package com.lemurian.bankdata.action.business;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.lemurian.bankdata.dto.LogHelper;
import com.lemurian.bankdata.lite.authentication.BankDataPrincipal;
import com.lemurian.bankdata.lite.enums.ApplicationCategory;
import com.lemurian.bankdata.lite.enums.UserActivityType;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.Pager;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.bankdata.lite.utils.GeneralConstant;
import com.lemurian.bankdata.lite.utils.GlobalFunction;
import com.lemurian.bankdata.services.ActivityLogService;
import com.lemurian.bankdata.services.BPNRegionListService;
import com.lemurian.bankdata.services.CategoryService;
import com.lemurian.bankdata.services.ClientService;
import com.lemurian.bankdata.services.ManagementService;
import com.lemurian.bankdata.services.SignatureScheduleService;
import com.lemurian.bankdata.utils.BaseAction;
import com.lemurian.entity.BPNRegionList;
import com.lemurian.entity.Category;
import com.lemurian.entity.Client;
import com.lemurian.entity.Management;
import com.lemurian.entity.SignatureSchedule;
import com.lemurian.entity.User;
import com.opensymphony.xwork2.Preparable;

public class KepengurusanAction extends BaseAction implements Preparable {

	private static final long serialVersionUID = 1L;

	private BankDataLogger log = BankDataLogger.getLogger(KepengurusanAction.class.getSimpleName());
	
	private int id = 0;
	private Management kepengurusan = null;
	
	private List<Management> listKepengurusan = new ArrayList<Management>();
	
	private int klienId = 0;
	private Client klien = null;
	
	private Integer kodeUrusanId = null;
	private List<Category> listKodeUrusan = new ArrayList<Category>();
	
	private int wilayahBPNId = 0;
	private List<BPNRegionList> listWilayahBPN = new ArrayList<BPNRegionList>();
	
	private String tanggalBPNMasuk;
	private String tanggalBPNSelesai;
	private String tanggalPengiriman;
	
	private String namaDebitur = "";
		
	private User user;
	private BankDataPrincipal principal;
	
	private DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
	private DateFormat dateOnly = new SimpleDateFormat("dd-MM-yyyy");
	
	@Autowired private SignatureScheduleService signatureScheduleService;
	@Autowired private ManagementService kepengurusanService;
	@Autowired private CategoryService categoryService;
	@Autowired private ClientService klienService;
	@Autowired private BPNRegionListService bpnRegionListService;
	
	@Autowired 
	private ActivityLogService userActivityLogService;
	private LogHelper userActivityLog;
	
	private static final String FILE_LOCATION = ServletActionContext.getServletContext().getRealPath("jasper/hasil_pengecekan_sertifikat.jasper");
	private static final String IMAGE_LOCATION = ServletActionContext.getServletContext().getRealPath("");
	
	// download
	private String downloadContentType;
	private InputStream inputStream;
	private String downloadFileName;
	
	@Override
	public void prepare() throws Exception {
		principal = (BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL);
		user = principal.getUser();
		
		log.sInfo("get kepengurusan id [%s]", id);
        if (id > 0) {
        	kepengurusan = kepengurusanService.findByIdJoinManagementType(id);
        	if (kepengurusan != null) {
        		log.info("found kepengurusan with that id");				
        	} else {
        		log.info("klien was not found");
        	}
        }
	}

	@Override
	@SkipValidation
	public String list() {		
		log.info("list kepengurusan");
		setPreviousPage(GeneralConstant.LIST);
		try {
			PartialList<Management> partialList = kepengurusanService.findByCriteria(getStart(), getCount(),
					getAscDesc().equalsIgnoreCase("desc") ? Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "createDate") : Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "createDate"),
	                namaDebitur != null && namaDebitur.length() > 0 ? Restrictions.ilike("debitur.name", namaDebitur, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
	                Restrictions.eq("signatureStatus", true)
					);
	
	        listKepengurusan = partialList.getList();
	        log.sInfo("found [%s] kepengurusan", listKepengurusan.size());
	
	        setPager(Pager.generatePager(getStart(), getCount(), partialList.getTotal()));
	        setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialList.getTotal()));
	
	        partialList = null;
	
		} catch (Exception e) {
			e.printStackTrace();
		}
	    setMappedRequest(GeneralConstant.LIST);
	    return SUCCESS;

	}

	@Override
	@SkipValidation
	public String add() {
		log.info("on input form penandatanganan page ..");
	    setMappedRequest(GeneralConstant.SAVE);
	    setPreviousPage(GeneralConstant.ADD);
	    
	    try {
	    	if (kepengurusan.getManagementType().getParent().getId() == ApplicationCategory.KEPENGURUSAN_PPAT.code()) {
	    		listKodeUrusan = categoryService.findByCriteria(Order.asc("id"),(Restrictions.eq("parent.id", ApplicationCategory.KODE_URUSAN_PPAT.code())));
	    		log.sInfo("found listKodeKepengurusan for PPAT [%s]", listKodeUrusan.size());	
		    	
			} else if (kepengurusan.getManagementType().getParent().getId() == ApplicationCategory.KEPENGURUSAN_NOTARIS.code()) {
	    		listKodeUrusan = categoryService.findByCriteria(Order.asc("id"),(Restrictions.eq("parent.id", ApplicationCategory.KODE_URUSAN_NOTARIS.code())));
		    	log.sInfo("found listKodeKepengurusan for Notaris [%s]", listKodeUrusan.size());	
			}
	    	
	    	listWilayahBPN = bpnRegionListService.findAll(Order.asc("reqionName"));
	    	log.sInfo("found listWilayahBPN [%s]", listWilayahBPN.size());
	    	
	    	if (kepengurusan.getBpnRegion() != null) {
				wilayahBPNId = kepengurusan.getBpnRegion().getId();
			}
	    	
	    	if (kepengurusan.getOccasionsCode() != null) {
				kodeUrusanId = kepengurusan.getOccasionsCode().getId();
			}
	    	
	    	if (kepengurusan.getInBPNDate() != null) {
				tanggalBPNMasuk = dateOnly.format(kepengurusan.getInBPNDate());
			}
	    	
	    	if (kepengurusan.getOutBPNDate() != null) {
				tanggalBPNSelesai = dateOnly.format(kepengurusan.getOutBPNDate());
			}
	    	
	    	if (kepengurusan.getSendDate() != null) {
				tanggalPengiriman = dateOnly.format(kepengurusan.getSendDate());
			}
	    			
		} catch (Exception e) {
			e.printStackTrace();
		}
	    
	    return SUCCESS;
	}

	@Override
	public String save() {
		log.info("on save klien action .. ");
		try {
			log.sInfo("Kepengurusan process [%s]", kepengurusan.getProcess());
			log.sInfo("Kepengurusan klien [%s]", kepengurusan.getClient());
			
			if (wilayahBPNId != 0) {
				BPNRegionList wilayah = bpnRegionListService.findById(wilayahBPNId);
				log.sInfo("found wilayah [%s]", wilayah.getReqionName());
				kepengurusan.setBpnRegion(wilayah);
			}
			
			if (kodeUrusanId != null) {
				Category kodeUrusan = categoryService.findById(getKodeUrusanId());
				log.sInfo("found kode urusan [%s]", kodeUrusan.getName());
				kepengurusan.setOccasionsCode(kodeUrusan);
			}
			
			if (tanggalBPNMasuk != null && !tanggalBPNMasuk.equalsIgnoreCase("")) {
				Date date = df.parse(tanggalBPNMasuk + " 00:00");
				log.sInfo("Tanggal bpn masuk [%s]", date);
				kepengurusan.setInBPNDate(date);
			}
			
			if (tanggalBPNSelesai != null && !tanggalBPNSelesai.equalsIgnoreCase("")) {
				Date date = df.parse(tanggalBPNSelesai + " 00:00");
				log.sInfo("Tanggal bpn selesai [%s]", date);
				kepengurusan.setOutBPNDate(date);
			}
			
			if (tanggalPengiriman != null && !tanggalPengiriman.equalsIgnoreCase("")) {
				Date date = df.parse(tanggalPengiriman + " 00:00");
				log.sInfo("Tanggal pengiriman [%s]", date);
				kepengurusan.setSendDate(date);
			}
			
			kepengurusanService.save(kepengurusan);
			addCustomActionMessage("Data kepengurusan berhasil disimpan");
			
			userActivityLog = new LogHelper(user, UserActivityType.UPDATE_BPN_PROCESS);
			
            try {
                log.sInfo(" :: User [%s:%s] is successfully updated status of bpn process of [%s]", user.getId(), user.getName(), kepengurusan.getClient().getDebitur().getName());

                //check if activity is success
                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
            } catch (Exception e) {
                log.sInfo(" :: Error was raised when User [%s:%s] updated schedule signature of [%s]", user.getId(), user.getName(), kepengurusan.getClient().getDebitur().getName());
                
                //set activity log status into failed
                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
                userActivityLog.setErrorMsg(e.getMessage());
            }
            //save activity log
            userActivityLog.setSessionId(ServletActionContext.getRequest().getSession().getId());
            userActivityLog.getAdditionalParams().add(kepengurusan.getClient().getDebitur().getName());
            userActivityLogService.saveUserActivity(userActivityLog);
			
		} catch (Exception e) {
			addCustomActionMessage("Maaf terjadi kesalahan : " + e.getMessage());
			e.printStackTrace();
		}

		setMappedRequestFullPath("/KepengurusanAction_list.do");
		return GeneralConstant.REDIRECT;
	}
	
	public String pdf() {
		return "download";
	}
	
	public String excel() {
		return "download";
	}

	@Override
	@SkipValidation
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String update() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@SkipValidation
	public String detail() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@SkipValidation
	public String delete() {
		// TODO Auto-generated method stub
		return null;
	}

	public int getId() {
		return id;
	}

	public void setId(String id) {
		int id_ = 0;
		if(id != null && !id.equalsIgnoreCase("0")) {
			id = GlobalFunction.decodeParameter(id);
	        id_ = Integer.parseInt(id);
		}
        this.id = id_;
	}

	public Management getKepengurusan() {
		return kepengurusan;
	}

	public void setKepengurusan(Management kepengurusan) {
		this.kepengurusan = kepengurusan;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Integer getKodeUrusanId() {
		System.out.println("get kode urusan : " + kodeUrusanId);
		return kodeUrusanId;
	}

	public void setKodeUrusanId(String kodeUrusanId) {
		Integer id_ = null;
		if(kodeUrusanId != null && !kodeUrusanId.equalsIgnoreCase("")) {
			System.out.println(" set kodeurusan : " + kodeUrusanId);
			kodeUrusanId = GlobalFunction.decodeParameter(kodeUrusanId);
	        id_ = Integer.parseInt(kodeUrusanId);
	        System.out.println("set id : " + id_);
		}
        this.kodeUrusanId = id_;
	}

	public List<Category> getListKodeUrusan() {
		return listKodeUrusan;
	}

	public void setListKodeUrusan(List<Category> listKodeUrusan) {
		this.listKodeUrusan = listKodeUrusan;
	}

	public int getKlienId() {
		return klienId;
	}

	public void setKlienId(String klienId) {
		int id_ = 0;
		if(klienId != null && !klienId.equalsIgnoreCase("0")) {
			klienId = GlobalFunction.decodeParameter(klienId);
	        id_ = Integer.parseInt(klienId);
		}
        this.klienId = id_;
	}

	public List<BPNRegionList> getListWilayahBPN() {
		return listWilayahBPN;
	}

	public void setListWilayahBPN(List<BPNRegionList> listWilayahBPN) {
		this.listWilayahBPN = listWilayahBPN;
	}

	public int getWilayahBPNId() {
		System.out.println("get wilayah id : " + wilayahBPNId);
		return wilayahBPNId;
	}

	public void setWilayahBPNId(String wilayahBPNId) {
		int id_ = 0;
		if(wilayahBPNId != null && !wilayahBPNId.equalsIgnoreCase("0")) {
			System.out.println("set wilayah id : " + wilayahBPNId);
			wilayahBPNId = GlobalFunction.decodeParameter(wilayahBPNId);
	        id_ = Integer.parseInt(wilayahBPNId);
	        System.out.println("id : " + id_);
		}
        this.wilayahBPNId = id_;
	}

	public String getTanggalBPNMasuk() {
		return tanggalBPNMasuk;
	}

	public void setTanggalBPNMasuk(String tanggalBPNMasuk) {
		this.tanggalBPNMasuk = tanggalBPNMasuk;
	}

	public String getTanggalBPNSelesai() {
		return tanggalBPNSelesai;
	}

	public void setTanggalBPNSelesai(String tanggalBPNSelesai) {
		this.tanggalBPNSelesai = tanggalBPNSelesai;
	}

	public String getNamaDebitur() {
		return namaDebitur;
	}

	public void setNamaDebitur(String namaDebitur) {
		this.namaDebitur = namaDebitur;
	}

	public String getTanggalPengiriman() {
		return tanggalPengiriman;
	}

	public void setTanggalPengiriman(String tanggalPengiriman) {
		this.tanggalPengiriman = tanggalPengiriman;
	}

	public List<Management> getListKepengurusan() {
		return listKepengurusan;
	}

	public void setListKepengurusan(List<Management> listKepengurusan) {
		this.listKepengurusan = listKepengurusan;
	}
}